import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:ost_flutter_module/common/color.dart';
import 'package:ost_flutter_module/common/empty_page.dart';
import 'package:ost_flutter_module/widget/custom_widget/custom_search_app_bar.dart';
import 'package:ost_flutter_module/widget/loading/loading_empty_widget.dart';
import 'package:ost_flutter_module/widget/loading/loading_error_widget.dart';
import 'package:ost_flutter_module/widget/loading/loading_view.dart';
import 'package:ost_flutter_module/widget/loading/loading_widget.dart';

import 'bloc/store_search_bloc.dart';
import 'store_search_result_page.dart';

class StoreSearchPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<StoreSearchBloc>(
      create: (context) => StoreSearchBloc(),
      child: StoreSearchAppBar(),
    );
  }
}

class StoreSearchAppBar extends StatefulWidget {
  const StoreSearchAppBar({Key key}) : super(key: key);

  @override
  _StoreSearchAppBarState createState() => _StoreSearchAppBarState();
}

class _StoreSearchAppBarState extends State<StoreSearchAppBar> {
  String keyword = '';

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<StoreSearchBloc, StoreSearchState>(
        builder: (context, state) {
      var _dataModel = context.read<StoreSearchBloc>().dataModel;

      return Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: colorFAFAFA,
          elevation: 0,
          title: GSearchAppBar(
            hintText: '请输入',
            onChanged: (value) {},
            onClear: () {
              keyword = '';
              setState(() {});
            },
            onSearch: (value) {
              if (value.isNotEmpty) {
                keyword = value;
                setState(() {});
                context
                    .read<StoreSearchBloc>()
                    .add(StoreSearchFetchEvent(query: value));
              }
            },
            onCancel: () {
              Navigator.pop(context);
            },
          ),
        ),
        body: _dataModel.entity == null
            ? Container()
            : LoadingView(
                status: _dataModel?.loadingStatus,
                loadingContent: LoadingWidget(),
                errorContent: LoadingErrorWidget(
                  errorTitle: _dataModel?.errorMsg,
                  onRetry: () =>
                      context.read<StoreSearchBloc>().add(StoreSearchFetchEvent(
                            // isRefresh: true,
                            query: keyword,
                          )),
                ),
                successContent:
                    StoreSearchResultPage(entity: _dataModel.entity),
                emptyContent: LoadingEmptyWidget(),
              ),
      );
    });
  }
}
